/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dopdf.io;

import org.dopdf.document.model.ResourceDetail;
import org.dopdf.utils.Constants;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * The class that reads a jar based resource and provides method to directly get all its data as bytes.
 *
 * @author Deep Shah
 */
public class JarResource {

    /** The logger. */
    private static final Logger logger = Logger.getLogger(JarResource.class.toString());

    /** The resource path. */
    private String path;

    /**
     * The constructor that takes in the resource path as argument.
     * @param path the path of the resource that we are interested in.
     */
    public JarResource(final String path) {
        this.path = path;
    }

    /**
     * The method that will read all data of the resource at a given path and return its bytes.
     * @return the ResourceDetail of the resource represented by the path.
     */
    public ResourceDetail getResourceDetail() {

        try {
            final InputStream inputStream = getClass().getResourceAsStream(path);

            if(inputStream == null) return null;

            final int size = inputStream.available();
            byte[] data = new byte[size];
            int bytesRead;
            int offset = 0;
            while (offset < data.length && (bytesRead = inputStream.read(data, offset, data.length - offset)) >= 0) {
                offset += bytesRead;
            }
            inputStream.close();
            return new ResourceDetail(data, new ContentTypeResolver(path).getType());
        } catch (final IOException e) {
            logger.log(Level.SEVERE, e.getMessage(), e);
            return null;
        }
    }
}
